<?php
////////////////////////////////////////////////////
//	LinBoard
//	Framework/Mysql.php
//	Created: 18th February 2009; 16:17 UTC
//	LinBoard (c) Copyright OpenInferno 2008, 2009
////////////////////////////////////////////////////

//Setup Environment
error_reporting(E_ALL | E_STRICT);

//Direct Access Check
if(!defined("LINBOARD"))
{
	die("<h1>Access Error</h1>Direct Access to this script is forbidden.");
}

class Mysql
{
	var $handle;
	var $result;
	var $queries = 0;
	var $querylog = array();
	
	public function __destruct()
	{
		if($this->isConnected())
		{
			$this->close();
		}
	}
	
	public function connect($host, $username, $password)
	{
		$this->handle = mysql_connect($host, $username, $password);
		if($this->handle == null)
		{
			die("Unable to establish connection with database");
		}
		return $this->handle;
	}
	
	public function isConnected()
	{
		if(is_object($this->handle))
		{
			return true;
		} else {
			return false;
		}
	}
	
	public function selectDatabase($database)
	{
		if(!mysql_select_db($database, $this->handle))
		{
			die("Unable to select database");
		}
	}
	
	public function query($query)
	{
		$this->result = mysql_query($query, $this->handle) or die("Mysql Error: ".mysql_error().'<br />'.$query);
		$this->querylog[] = $query;
		$this->queries++;
		return $this->result;
	}
	
	public function fetchArray($result)
	{
		return mysql_fetch_array($result);
	}
	
	public function freeResult($result)
	{
		mysql_free_result($result);
	}
	
	public function numRows($result)
	{
		return mysql_num_rows($result);
	}
	
	public function escapeString($string)
	{
		return mysql_real_escape_string($string);
	}
	
	public function lastInsertID($bigint)
	{
		if($bigint)
		{
			$result = Framework::Mysql()->query("SELECT LAST_INSERT_ID() as lid;");
			$result = Framework::Mysql()->fetchArray($result);
			return $result['lid'];
		} else {
			return mysql_insert_id();
		}
	}
	
	public function close()
	{
		mysql_close($this->handle);
	}
	
	public function requireConnection()
	{
		if(!$this->isConnected())
		{
			$this->connect(Framework::Config()->Mysql['host'], Framework::Config()->Mysql['username'], Framework::Config()->Mysql['password']);
			$this->selectDatabase(Framework::Config()->Mysql['database']);
		}
	}
	
	public static function getInstance()
	{
		static $instance;
		if(!isset($instance))
		{
			$class = __CLASS__;
			$instance = new $class;
		}
		return $instance;
	}
	
}

?>